# -*- coding: utf-8 -*-
# created on 2016/12/06
from mathsolver.functions.shulie.QianNXiangHe import ShuLieQiuHe
from mathsolver.functions.shulie.ShuLie_getSums import ShuLieGetSums
from mathsolver.functions.shulie.QianNXiangHe import ShuLieQiuHe
from mathsolver.functions.base import *
from sympy.abc import n
from mathsolver.functions.shulie.ShuLie_getSeqPoly import ShuLieGetSeqPoly
from mathsolver.functions.shulie.Distinguish import *
from sympy import fraction


def inf_sums_anames(expr):
    a_names = []
    a_name = None
    for i, item in enumerate(expr.split('+')):
        try:
            val = sympify(item, evaluate=False)
            a_name = val.func
        except Exception:
            pass
        a_names.append(a_name)
    a_names = set(a_names)
    a_names = list(a_names)
    return a_names


def inf_sums_items(expr):
    items = []
    for i, item in enumerate(expr.split('+')):
        try:
            val = sympify(item, evaluate=False)  # evluate=False => 分子分母不自动化简
        except Exception:
            val = None
        items.append(val)
    return items


def inf_sums_indexs(items):
    indexs = []
    for item in items:
        try:
            index = item.args[0]
        except Exception:
            index = None
        indexs.append(index)
    return indexs


def inf_sums_tongxiang(indexs):
    tongxiang = None
    d = indexs[1] - indexs[0]
    if indexs[2]:
        d2 = indexs[2] - indexs[1]
        if d == d2:
            tongxiang = indexs[0] + (n - 1) * d
    else:
        tongxiang = indexs[0] + (n - 1) * d
    return tongxiang


class ShuLieGetInfSums001(BaseFunction):
    """
    如果等差数列{a_{n}}中,a_{3}+a_{4}+a_{5}=12,那么a_{1}+a_{2}+…+a_{7}=()
    """
    def solver(self, *args):
        inf_poly = args[0].value
        inf_poly_a_names = inf_sums_anames(inf_poly)
        inf_poly_items = inf_sums_items(inf_poly)
        inf_poly_indexs = inf_sums_indexs(inf_poly_items)
        inf_poly_tong_xiang = inf_sums_tongxiang(inf_poly_indexs)
        if len(inf_poly_a_names) == 1:
            a_name = inf_poly_a_names[0]
            stepsolver = ShuLieGetSeqPoly(self.known).solver(BasePoly(a_name(n)))
            self.steps += stepsolver.steps
            self.label.update(stepsolver.label)
            tong_xiangs = stepsolver.output[0].sympify()
            tong_xiang = tong_xiangs[0]
            new_items = []
            for item in inf_poly_indexs:
                try:
                    val = tong_xiang.subs({n: item})
                except Exception:
                    val = None
                new_items.append(val)
            if sl_linear_n(inf_poly_tong_xiang, n):
                a, b = sl_linear_poly_coeffs(inf_poly_tong_xiang, n)
                num = (inf_poly_indexs[-1] - inf_poly_indexs[0]) / a + 1
                if num == sympify('n'):
                    tong_xiang = tong_xiang.subs({sympify('n'): inf_poly_tong_xiang})
                stepsolver = ShuLieQiuHe().solver([a_name(n), tong_xiang], 1, num)
                n_sums = stepsolver.output[0].sympify()
                n_sums = n_sums[0]
                self.steps.append(["", "%s的值为%s" % (inf_poly, new_latex(n_sums))])
        return self


class ShuLieGetInfSums002(BaseFunction):
    """
    等比数列{a_{n}}的各项均为正数,2a_{1}+3a_{2}=1,a_{3}^{2}=9a_{2}a_{6},设b_{n}=log_{3}a_{1}+log_{3}a_{2}+…+log_{3}a_{n},求数列{\\frac{1}{{b}_{n}}}的前n项和.
    """
    def solver(self, *args):
        inf_poly = args[0].value
        inf_poly_items = inf_sums_items(inf_poly)
        last_item = inf_poly_items[-1]
        last_item_symbols = last_item.free_symbols
        assert last_item_symbols
        try:
            stepsolver1 = ShuLieGetSeqPoly(self.known).solver(BasePoly(last_item))
        except Exception:
            raise Exception('Try Error!')
        self.steps += stepsolver1.steps
        self.label.update(stepsolver1.label)
        last_item_values = stepsolver1.output[0].sympify()
        assert len(last_item_values) == 1
        last_item_value = last_item_values[0]
        if str(last_item_value).find(str("log")) >= 0:
            fenzhi, fenmu = fraction(last_item_value)
            if str(fenzhi.func) == str("log") and str(fenmu.func) == str("log"):
                fenzhi_value = fenzhi.args[0]
                fenmu_value = fenmu.args[0]
                if isinstance(fenzhi_value, Pow):
                    base_, exp = fenzhi_value.args
                    if base_ - fenmu_value == 0:
                        last_item_value = exp
        a_name = sympify('c_')
        symbol = list(last_item.free_symbols)[0]
        self.steps.append(["", "设%s = %s, 则" % (new_latex(a_name(n)), new_latex(last_item_value))])
        stepsolver2 = ShuLieQiuHe().solver([a_name(n), last_item_value], 1, symbol)
        self.steps += stepsolver2.steps
        self.label.update(stepsolver2.label)
        n_sums = stepsolver2.output[0].sympify()
        n_sums = n_sums[0]
        self.steps.append(["", "%s的值为%s" % (inf_poly, new_latex(n_sums))])
        self.output.append(BaseNumbers([n_sums]))
        return self


class ShuLieGetInfSums(BaseFunction):
    CLS = [ShuLieGetInfSums001, ShuLieGetInfSums002]

    def solver(self, *args):
        r = None
        known = dict(self.known)
        for cl in ShuLieGetInfSums.CLS:
            try:
                r = cl(known, verbose=True).solver(*args)
                break
            except Exception:
                pass
        if not r:
            raise 'try fail'
        return r


if __name__ == '__main__':
    pass
